package com.activeMQ.student.transcation;

import lombok.SneakyThrows;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * 异步的队列消费者
 * @date 2020/10/7 14:41
 */
public class TestSyncConsumer {

    private static String brokerUrl = "tcp://106.12.51.117:61617";

    private static String queueName = "First-Message";

    public static void main(String[] args) throws JMSException, IOException {

        ConnectionFactory factory = new ActiveMQConnectionFactory(brokerUrl);
        Connection connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(queueName);
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(new MessageListener() {
            @SneakyThrows
            public void onMessage(Message message) {
                if (message instanceof  TextMessage){
                    TextMessage textMessage = (TextMessage) message;
                        System.out.println(textMessage.getText());
                }
            }
        });


//        不让程序结束
        System.in.read();

//        关机资源
        consumer.close();
        session.close();
        connection.close();

        System.out.println("消息接收成功");
    }

}
